<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Document,
  Promotion,
  Plus,
  Picture,
  Delete,
  Loading
} from '@element-plus/icons-vue'
import { listCategory } from "@/api/information/information.js"
import { addInformation } from "@/api/information/information.js"
import { uploadImg } from "@/api/information/information.js" // 引入新的上传接口

const router = useRouter()

// 响应式数据
const categoryList = ref([])
const loading = ref(false)
const uploadLoading = ref(false)

const formData = reactive({
  title: '',
  categoryId: null,
  coverImage: '',
  content: '',
  author: '',
  source: '1',
  isTop: '0',
  isHot: '0',
  status: '',
  publishTime: new Date()
})

// 获取栏目列表
const getCategoryList = async () => {
  try {
    const response = await listCategory()
    categoryList.value = response.data || []
  } catch (error) {
    console.error('获取栏目列表失败:', error)
    ElMessage.error('获取栏目列表失败')
    categoryList.value = []
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 封面图上传前验证
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  // 验证通过后自动上传
  return true
}

// 自定义上传方法
const handleCoverUpload = async (file) => {
  uploadLoading.value = true

  // 创建 FormData 对象
  const formDataObj = new FormData()
  formDataObj.append('file', file.file)

  try {
    const response = await uploadImg(formDataObj)
    console.log('上传完整响应:', response) // 查看完整响应结构

    if (response.code === 200) {
      // 根据响应结构，图片URL在 msg 字段中
      formData.coverImage = response.msg // 修改这里：使用 response.msg
      console.log('设置的封面图URL:', formData.coverImage)
      ElMessage.success('封面图上传成功')
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败: ' + (error.message || '未知错误'))
  } finally {
    uploadLoading.value = false
  }
}

// 移除封面图
const removeCover = () => {
  formData.coverImage = ''
}

// 保存为草稿
const saveAsDraft = async () => {
  if (!validateForm()) return

  loading.value = true
  try {
    const submitData = {
      title: formData.title,
      categoryId: formData.categoryId,
      coverImage: formData.coverImage, // 确保包含封面图
      content: formData.content,
      author: formData.author,
      source: formData.source,
      isTop: formData.isTop,
      isHot: formData.isHot,
      status: '3', // 草稿状态
      publishTime: formData.publishTime
    }

    console.log('提交的数据:', JSON.stringify(submitData, null, 2))
    console.log('封面图URL:', submitData.coverImage)

    const response = await addInformation(submitData)
    console.log('保存响应:', response)

    if (response.code === 200) {
      ElMessage.success('保存草稿成功')
      router.push('/userIndex/information')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 发布资讯
const publishArticle = async () => {
  if (!validateForm()) return

  try {
    await ElMessageBox.confirm(
        '确定要发布这篇资讯吗？发布后需要等待审核通过才能显示。',
        '发布确认',
        {
          confirmButtonText: '确定发布',
          cancelButtonText: '再想想',
          type: 'warning'
        }
    )

    loading.value = true
    const submitData = {
      title: formData.title,
      categoryId: formData.categoryId,
      coverImage: formData.coverImage,
      content: formData.content,
      author: formData.author,
      source: formData.source,
      isTop: formData.isTop,
      isHot: formData.isHot,
      status: '0', // 待审核状态
      publishTime: formData.publishTime
    }

    console.log('发布提交的数据:', JSON.stringify(submitData, null, 2))
    console.log('发布封面图URL:', submitData.coverImage)

    const response = await addInformation(submitData)
    console.log('发布响应:', response)

    if (response.code === 200) {
      ElMessage.success('发布成功，等待审核')
      router.push('/userIndex/information')
    } else {
      ElMessage.error(response.msg || '发布失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布失败:', error)
      ElMessage.error('发布失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}
// 表单验证
const validateForm = () => {
  if (!formData.title.trim()) {
    ElMessage.error('请输入资讯标题')
    return false
  }
  if (!formData.categoryId) {
    ElMessage.error('请选择栏目')
    return false
  }
  if (!formData.content.trim()) {
    ElMessage.error('请输入资讯内容')
    return false
  }
  return true
}

// 初始化
onMounted(() => {
  getCategoryList()
})
</script>

<template>
  <div class="publish-page">
    <div class="publish-container">
      <!-- 顶部标题栏 -->
      <div class="publish-header">
        <div class="header-left">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
        <div class="header-center">
          <h2>发布资讯</h2>
        </div>
        <div class="header-right">
          <el-button
              type="primary"
              @click="saveAsDraft"
              :loading="loading"
              class="draft-btn"
          >
            <el-icon><Document /></el-icon>
            存草稿
          </el-button>
          <el-button
              type="primary"
              @click="publishArticle"
              :loading="loading"
              class="publish-btn"
          >
            <el-icon><Promotion /></el-icon>
            发布
          </el-button>
        </div>
      </div>

      <!-- 内容编辑区域 -->
      <div class="editor-container">
        <!-- 标题输入 -->
        <div class="title-section">
          <el-input
              v-model="formData.title"
              placeholder="请输入资讯标题..."
              maxlength="100"
              show-word-limit
              class="title-input"
          />
        </div>

        <!-- 栏目选择 -->
        <div class="category-section">
          <el-select
              v-model="formData.categoryId"
              placeholder="请选择栏目"
              clearable
              class="category-select"
          >
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            />
          </el-select>
        </div>

        <!-- 封面图上传 -->
        <div class="cover-section">
          <div class="section-label">封面图</div>
          <el-upload
              class="cover-upload"
              :action="''"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :http-request="handleCoverUpload"
              :disabled="uploadLoading"
          >
            <div class="upload-area" v-if="!formData.coverImage">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">上传封面图</div>
              <div class="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</div>
            </div>
            <div v-else class="cover-preview">
              <el-image
                  :src="formData.coverImage"
                  fit="cover"
                  class="cover-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="cover-actions">
                <el-button
                    type="danger"
                    size="small"
                    @click.stop="removeCover"
                    circle
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </el-upload>
          <div v-if="uploadLoading" class="upload-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            上传中...
          </div>
        </div>

        <!-- 其他部分保持不变 -->
        <div class="content-section">
          <div class="section-label">资讯内容</div>
          <div class="editor-wrapper">
            <el-input
                v-model="formData.content"
                type="textarea"
                :rows="15"
                placeholder="请输入资讯内容..."
                maxlength="5000"
                show-word-limit
                resize="none"
                class="content-editor"
            />
          </div>
        </div>

        <div class="meta-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="meta-item">
                <label class="meta-label">作者</label>
                <el-input
                    v-model="formData.author"
                    placeholder="请输入作者名称"
                    maxlength="50"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="meta-item">
                <label class="meta-label">来源</label>
                <div class="source-radio-group">
                  <el-radio-group v-model="formData.source">
                    <el-radio label="1" size="large" class="source-radio">
                      <span class="radio-text">自制原创</span>
                    </el-radio>
                    <el-radio label="0" size="large" class="source-radio">
                      <span class="radio-text">网络转载</span>
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="options-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="option-item">
                <el-checkbox v-model="formData.isTop" true-label="1" false-label="0">
                  置顶显示
                </el-checkbox>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.publish-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  padding: 0;
}

.publish-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  min-height: 100vh;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.publish-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: white;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-center h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
  font-weight: 600;
}

.header-right {
  display: flex;
  gap: 12px;
}

.back-btn {
  border: none;
  background: transparent;
  color: #666;
}

.back-btn:hover {
  background: #f5f5f5;
  color: #409eff;
}

.draft-btn {
  background: #909399;
  border-color: #909399;
}

.draft-btn:hover {
  background: #a6a9ad;
  border-color: #a6a9ad;
}

.publish-btn {
  background: #409eff;
  border-color: #409eff;
}

.editor-container {
  padding: 24px;
}

.title-section {
  margin-bottom: 24px;
}

.title-input :deep(.el-input__inner) {
  font-size: 1.5rem;
  font-weight: 600;
  border: none;
  border-bottom: 2px solid #f0f0f0;
  border-radius: 0;
  padding: 12px 0;
  height: auto;
}

.title-input :deep(.el-input__inner):focus {
  border-bottom-color: #409eff;
  box-shadow: none;
}

.category-section {
  margin-bottom: 24px;
}

.category-select {
  width: 200px;
}

.cover-section {
  margin-bottom: 24px;
}

.section-label {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 0.95rem;
}

.cover-upload {
  width: 100%;
}

.upload-area {
  width: 100%;
  height: 200px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.upload-area:hover {
  border-color: #409eff;
  background: #f0f7ff;
}

.upload-icon {
  font-size: 2rem;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.upload-text {
  color: #909399;
  font-size: 0.9rem;
}

.cover-preview {
  position: relative;
  width: 100%;
  max-width: 300px;
  border-radius: 8px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 200px;
  display: block;
}

.cover-actions {
  position: absolute;
  top: 8px;
  right: 8px;
}

.content-section {
  margin-bottom: 24px;
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
}

.content-editor :deep(.el-textarea__inner) {
  border: none;
  border-radius: 0;
  font-size: 1rem;
  line-height: 1.6;
  resize: none;
}

.meta-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-label {
  font-weight: 500;
  color: #606266;
  font-size: 0.9rem;
}

.source-radio-group {
  padding: 8px 0;
}

.source-radio {
  margin-right: 20px;
}

.radio-text {
  font-size: 0.9rem;
  color: #606266;
}

.options-section {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.option-item {
  display: flex;
  align-items: center;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #c0c4cc;
}

.image-error .el-icon {
  font-size: 2rem;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .publish-container {
    margin: 0;
  }

  .publish-header {
    padding: 12px 16px;
  }

  .editor-container {
    padding: 16px;
  }

  .header-center h2 {
    font-size: 1.25rem;
  }

  .title-input :deep(.el-input__inner) {
    font-size: 1.25rem;
  }

  .cover-preview {
    max-width: 100%;
  }

  .source-radio {
    display: block;
    margin-bottom: 12px;
  }
}
.upload-tip {
  font-size: 0.8rem;
  color: #909399;
  margin-top: 4px;
}

.upload-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  color: #409eff;
  font-size: 0.9rem;
}

.upload-loading .el-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>